//
//  MapVC.m
//  Run
//
//  Created by sxz on 16/4/1.
//  Copyright © 2016年 BetaTheta. All rights reserved.
//

#import "MapVC.h"
#import <MAMapKit/MAMapKit.h>
#import "BigView.h"
#import "SmallView.h"
#import "PointsModel.h"

@interface MapVC ()<MAMapViewDelegate>

@property (nonatomic, strong) UIButton *playBtu;
@property (nonatomic, strong) UIButton *endBtu;
@property (nonatomic, strong) UIButton *changeBtu;
@property (nonatomic, assign) BOOL isStart;
@property (nonatomic, assign) BOOL isFirst;
@property (nonatomic, assign) BOOL isChange;
@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) BigView *bigView;
@property (nonatomic, strong) SmallView *smallView;
@property (nonatomic, assign) CLLocationCoordinate2D lastPoint;
@property (nonatomic, strong) NSMutableArray *points;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSInteger time;
@property (nonatomic, assign) CGFloat distance;
@property (nonatomic, assign) CGFloat speed;

// 启动页
@property (nonatomic, strong)UIView *startView;
@property (nonatomic, strong)UILabel *countDown;

// CoreData存储数据
@property (nonatomic, strong) CoreDataManager *coreDataManager;
@property (nonatomic, strong) NSString *isSave;

@end


@implementation MapVC


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.isStart = NO;
    self.isFirst = YES;
    self.isChange = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    self.points = [NSMutableArray arrayWithCapacity:0];
    self.coreDataManager = [CoreDataManager shareCoreDataManager];
    [self createTimer];
    [self createMap];
    [self createStart];
    
}

#pragma mark - 启动页
- (void)createStart {
    
    self.startView = [[UIView alloc] initWithFrame:self.view.bounds];
    self.startView.backgroundColor = [UIColor greenColor];
    self.countDown = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    self.countDown.center = self.startView.center;
    self.countDown.textAlignment = NSTextAlignmentCenter;
    self.countDown.textColor = [UIColor whiteColor];
    self.countDown.font = [UIFont boldSystemFontOfSize:200];
    
    [self.startView addSubview:self.countDown];
    [self.view addSubview:self.startView];

}


#pragma mark - 定时器
- (void)createTimer {
    
    self.time = 0;
    self.distance = 0;
    self.speed = 0;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
    
}

- (void)timerAction:(NSTimer *)sender {
    
    if (self.time == 3) {
        [self.startView removeFromSuperview];
        self.isStart = YES;
    }
    
    if (self.countDown) {
        self.countDown.text = [NSString stringWithFormat:@"%ld", 3 - self.time];
    }
    
    if (self.isStart && (self.time > 3)) {
        self.bigView.timeNum.text = [self convertTime:self.time - 3];
        self.smallView.timeNum.text = [self convertTime:self.time - 3];
        if (self.distance >= 10) {
            self.bigView.distanceNum.text = [NSString stringWithFormat:@"%.2f", self.distance / 1000.0];
            self.smallView.distanceNum.text = [NSString stringWithFormat:@"%.2f", self.distance / 1000.0];
            
            if (self.time % 60 == 0) {
                self.speed = (self.distance / 1000.0) / (self.time / 60.0);
                self.bigView.speedNum.text = [NSString stringWithFormat:@"%0.2f", self.speed];
            }
        }
    
    }
    
    self.time++;
    
}

#pragma mark - Map
- (void)createMap {
    
    [MAMapServices sharedServices].apiKey = @"fa4dbd6236dd0c07acabc113594f482b";
    
    self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT / 4)];
    self.mapView.delegate = self;
//    显示用户位置
    self.mapView.showsUserLocation = YES;
//    指南针
    self.mapView.showsCompass = NO;
//    比例尺
    self.mapView.showsScale = NO;
    
    [self.mapView setUserTrackingMode:MAUserTrackingModeFollow animated:YES];
//    保持位置更新
    self.mapView.pausesLocationUpdatesAutomatically = NO;
//    后台位置更新
    self.mapView.allowsBackgroundLocationUpdates = YES;

//    启用用户交互
    self.mapView.userInteractionEnabled = YES;
    // 点击事件
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeAction:)];
//    [ self.mapView addGestureRecognizer:tap];

    
    [self.view addSubview:self.mapView];
    [self.mapView setZoomLevel:16.1 animated:YES];
    
    [self createBtu];
    [self createChangeBtu];
    [self createSmallView];
    [self createBigView];
    
}



#pragma mark - 地图定位
- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation {
    
    if (updatingLocation && self.isStart) {
    
        if (self.isFirst) {
            
            // 添加大头针
            MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];
            pointAnnotation.coordinate = userLocation.coordinate;
            [self.mapView addAnnotation:pointAnnotation];
            
            
            // 存储位置信息
            PointsModel *point = [[PointsModel alloc] init];
            point.latitude = userLocation.coordinate.latitude;
            point.longitude = userLocation.coordinate.longitude;
            [self.points addObject:point];
            
            self.lastPoint = userLocation.coordinate;
            self.isFirst = NO;
            
        } else {
            
            if (self.lastPoint.latitude != userLocation.coordinate.latitude || self.lastPoint.longitude != userLocation.coordinate.longitude) {
                
                // 得到两个点
                CLLocationCoordinate2D polyLineCoords[2];
                polyLineCoords[0] = self.lastPoint;
                polyLineCoords[1] = userLocation.coordinate;
                
                // 存储位置信息
                PointsModel *point = [[PointsModel alloc] init];
                point.latitude = userLocation.coordinate.latitude;
                point.longitude = userLocation.coordinate.longitude;
                [self.points addObject:point];
                    
                MAPolyline *polyLine = [MAPolyline polylineWithCoordinates:polyLineCoords count:2];
                [self.mapView addOverlay:polyLine];
                    
                // 计算距离
                MAMapPoint lastPoint = MAMapPointForCoordinate(self.lastPoint);
                MAMapPoint nowPoint = MAMapPointForCoordinate(userLocation.coordinate);
                CLLocationDistance distance = MAMetersBetweenMapPoints(lastPoint, nowPoint);
                self.distance += distance;
                
                self.lastPoint = userLocation.coordinate;
            }
            
        }
        
    }
    
}

// 自定义头针
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *reuseIndetifier = @"annotationReuseIndetifier";
        MAAnnotationView *annotationView = (MAAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation
                                                          reuseIdentifier:reuseIndetifier];
        }
        annotationView.image = [UIImage imageNamed:@"起"];
        //设置中心点偏移，使得标注底部中间点成为经纬度对应点
        annotationView.centerOffset = CGPointMake(0, -18);
        return annotationView;
    }
    return nil;
}

#pragma mark - 地图划线
- (MAOverlayView *)mapView:(MAMapView *)mapView viewForOverlay:(id <MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[MAPolyline class]])
    {
        MAPolylineView *polylineView = [[MAPolylineView alloc] initWithPolyline:overlay];
        
        polylineView.lineWidth = 3.f;
        polylineView.strokeColor = [UIColor colorWithRed:0 green:0 blue:1 alpha:1];
        polylineView.lineJoin = kCGLineJoinRound; //连接类型
        polylineView.lineCap = kCGLineCapRound; // 点的类型
        
        return polylineView;
    }
    return nil;
}


#pragma mark - 地图放大
- (void)createChangeBtu {
    
    self.changeBtu = [UIButton buttonWithType:UIButtonTypeSystem];
    self.changeBtu.frame = CGRectMake(WIDTH - 50, self.mapView.frame.size.height - 50, 40, 40);
    [self.changeBtu setImage:[[UIImage imageNamed:@"changeBig"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [self.changeBtu addTarget:self action:@selector(changeAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:self.changeBtu];
}

- (void)changeAction:(UIButton *)sender {
 
    if (self.isChange) {
        
        NSLog(@"changeSmall");
        [sender setImage:[[UIImage imageNamed:@"changeBig"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        [UIView animateWithDuration:0.5 animations:^{
            self.mapView.frame = CGRectMake(0, 0, WIDTH, HEIGHT / 4);
            self.changeBtu.frame = CGRectMake(WIDTH - 50, self.mapView.frame.size.height - 50, 40, 40);
            
            self.smallView.alpha = 0;
            self.bigView.alpha = 1;
            self.playBtu.alpha = 1;
            self.endBtu.alpha = 1;
            
        }];
        
    } else {
        NSLog(@"changeBig");
        [sender setImage:[[UIImage imageNamed:@"changSmall"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        [UIView animateWithDuration:0.5 animations:^{
            self.mapView.frame = CGRectMake(0, 0, WIDTH, HEIGHT*0.8);
            self.changeBtu.frame = CGRectMake(WIDTH - 50, self.mapView.frame.size.height - 50, 40, 40);
            
            self.smallView.alpha = 1;
            self.bigView.alpha = 0;
    
        }];
        self.playBtu.alpha = 0;
        self.endBtu.alpha = 0;
        
    }
    self.isChange = !self.isChange;
    
}


#pragma mark - smallView 
- (void)createSmallView {

    self.smallView = [[SmallView alloc] initWithFrame:CGRectMake(0, HEIGHT * 0.8, WIDTH, HEIGHT * 0.2)];
    self.smallView.backgroundColor = [UIColor whiteColor];
    self.smallView.alpha = 0;
    [self.view addSubview:self.smallView];
    
}

#pragma mark - bigView
- (void)createBigView {
    
    self.bigView = [[BigView alloc] initWithFrame:CGRectMake(0, self.mapView.frame.size.height, WIDTH, self.playBtu.frame.origin.y - self.mapView.frame.size.height - 20)];
    self.bigView.backgroundColor =[UIColor whiteColor];
    self.bigView.hidden = NO;
    [self.view addSubview:self.bigView];
    
}


#pragma mark - 按钮
- (void)createBtu {
    
    self.endBtu = [UIButton buttonWithType:UIButtonTypeSystem];
    self.endBtu.frame = CGRectMake(0, 0, WIDTH / 4, WIDTH / 4);
    self.endBtu.backgroundColor = [UIColor colorWithRed:0.502 green:0.000 blue:0.000 alpha:1.000];
    self.endBtu.center = CGPointMake(WIDTH / 2, HEIGHT / 5 * 4);
    
    self.endBtu.layer.cornerRadius = self.endBtu.frame.size.width / 2.0;
    self.endBtu.layer.masksToBounds = YES;
    [self.endBtu setImage:[[UIImage imageNamed:@"end"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [self.endBtu addTarget:self action:@selector(endAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:self.endBtu];
    
    self.playBtu = [UIButton buttonWithType:UIButtonTypeSystem];
    self.playBtu.frame = self.endBtu.frame;
    self.playBtu.center = self.endBtu.center;
    self.playBtu.backgroundColor = [UIColor colorWithRed:0.400 green:1.000 blue:0.400 alpha:1.000];
    self.playBtu.layer.cornerRadius = self.playBtu.frame.size.width / 2.0;
    self.playBtu.layer.masksToBounds = YES;
    [self.playBtu setImage:[[UIImage imageNamed:@"pause"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [self.playBtu addTarget:self action:@selector(playAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:self.playBtu];
    
    
}

- (void)endAction:(UIButton *)sender {
    
    if ((self.distance / 1000) < 0.10) {
        self.isSave = @"本次运动距离小于100米, 将不会保存";
    } else {
        self.isSave = @"确认退出本次运动?";
    }
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:self.isSave preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if ((self.distance / 1000) < 0.10) {
            [self dismissViewControllerAnimated:YES completion:^{
                }];
        } else {
            
            [self addRunData];
            [self dismissViewControllerAnimated:YES completion:^{
            }];
        }
        
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    [alert addAction:okAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:^{
    }];
    
}

- (void)playAction:(UIButton *)sender {
    
    if (self.isStart) {

        NSLog(@"pause");
        [self.timer setFireDate:[NSDate distantFuture]];
        [sender setImage:[[UIImage imageNamed:@"start"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        [UIView animateWithDuration:0.25 animations:^{
            self.playBtu.frame = CGRectMake(self.endBtu.frame.origin.x - self.playBtu.frame.size.width, self.endBtu.frame.origin.y, WIDTH / 4, WIDTH / 4);
            
            self.endBtu.frame = CGRectMake(self.endBtu.frame.origin.x + self.endBtu.frame.size.width, self.playBtu.frame.origin.y, WIDTH / 4, WIDTH / 4);
        }];
        
    } else {
        
        NSLog(@"start");
        [self.timer setFireDate:[NSDate distantPast]];
        [sender setImage:[[UIImage imageNamed:@"pause"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        [UIView animateWithDuration:0.25 animations:^{
            self.endBtu.frame = CGRectMake(0, 0, WIDTH / 4, WIDTH / 4);
            self.endBtu.center = CGPointMake(WIDTH / 2, HEIGHT / 5 * 4);
            
            self.playBtu.frame = self.endBtu.frame;
            self.playBtu.center = self.endBtu.center;
            
        }];
        
    }
    
    self.isStart = !self.isStart;
    
}

#pragma mark - 时间转换
- (NSString *)convertTime:(NSInteger)second {
    
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    second -= 3600 * 8;
    NSDate *d = [NSDate dateWithTimeIntervalSince1970:second];
    [fmt setDateFormat:@"HH:mm:ss"];
    NSString *showtimeNew = [fmt stringFromDate:d];
    return showtimeNew;
    
}

#pragma mark - 添加数据
- (void)addRunData {
    
    RunData *data = [NSEntityDescription insertNewObjectForEntityForName:@"RunData" inManagedObjectContext:self.coreDataManager.managedObjectContext];

    data.distance = [NSNumber numberWithDouble:self.distance];
    data.time = [NSNumber numberWithInteger:(self.time - 3)];
    data.speed = [NSNumber numberWithDouble:self.speed];
    
    [self.coreDataManager saveContext];
    
    // 存储
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths lastObject];
    
    NSLog(@"run%ld%.f%.f", self.time - 3, self.distance, self.speed);
    
    NSString *str = [NSString stringWithFormat:@"run%ld%.f%.f", self.time - 3, self.distance, self.speed];
    path = [path stringByAppendingString:[NSString stringWithFormat:@"/%ld.plist", [str hash]]];
     NSLog(@"%@", path);
    [NSKeyedArchiver archiveRootObject:self.points toFile:path];
    
}


@end
